<template>
    <el-form-item>
        <el-button @click="onSubmit">保存修改信息</el-button>
    </el-form-item>
    <h2 style="margin-left: 400px;">交接任务单据</h2>
    <table class="order-table">
        <tr>
            <th colspan="6" style="text-align: left;">基本信息</th>
        </tr>
        <tr>
            <td>业务单号：</td>
            <td><el-input v-model="form.teamNumber" disabled/></td>
            <td>工厂：</td>
            <td><el-input v-model="form.factory" disabled/></td>
        </tr>
        <tr>
            <td>车间：</td>
            <td>
                <el-select v-model="form.workshop" placeholder="请选择车间" @change="updateDepartmentOptions" disabled>
                    <el-option label="酿造车间" value="酿造车间" />
                    <el-option label="糖化车间" value="糖化车间" />
                    <el-option label="过滤车间" value="过滤车间" />
                </el-select>
            </td>
            <td>部门：</td>
            <td>
                <el-select v-model="form.department" placeholder="请选择部门" disabled>
                    <el-option v-for="option in departmentOptions" :key="option.value" :label="option.label" :value="option.value" />
                </el-select>
            </td>
        </tr>
        <tr>
            <td>产线：</td>
            <td>
                <el-select v-model="form.productionLine" placeholder="请选择产线" disabled>
                    <el-option v-for="option in productionLineOptions" :key="option.value" :label="option.label" :value="option.value" />
                </el-select>
            </td>
            <td>班组：</td>
            <td><el-input v-model="form.teams" /></td>
        </tr>
        <tr>
            <td>班次：</td>
            <td>
                <el-select v-model="form.shift" placeholder="请选择班次">
                    <el-option label="白班" value="白班" />
                    <el-option label="夜班" value="夜班" />
                </el-select>
            </td>
            <td>状态：</td>
            <td>
                <span>{{ stateText }}</span>
                <input type="hidden" v-model="form.state">
            </td>
        </tr>
        <tr>
            <td>日期：</td>
            <td>
                <el-date-picker v-model="form.date" type="datetime" placeholder="Pick a date" style="width: 100%" disabled/>
            </td>
            <td>记录人：</td>
            <td><el-input v-model="form.recorders" disabled/></td>
        </tr>
        <tr>
            <td>交班班长：</td>
            <td>
                <el-select v-model="form.shiftleader" placeholder="请选择交班班长" disabled>
                    <el-option label="秦卓珈" value="秦卓珈" />
                    <el-option label="韩一芳" value="韩一芳" />
                    <el-option label="刘志宝" value="刘志宝" />
                    <el-option label="申莹洋" value="申莹洋" />
                    <el-option label="周岚青" value="周岚青" />
                    <el-option label="徐如华" value="徐如华" />
                    <el-option label="张淑馨" value="张淑馨" />
                    <el-option label="郭银汝" value="郭银汝" />
                    <el-option label="屈语盼" value="屈语盼" />
                    <el-option label="柳泳辉" value="柳泳辉" />
                </el-select>
            </td>
            <td>接班班长：</td>
            <td>
                <el-select v-model="form.successionMonitor" placeholder="请选择接班班长" disabled>
                    <el-option label="陶颢瑶" value="陶颢瑶" />
                    <el-option label="孟轩" value="孟轩" />
                    <el-option label="甄茹语" value="甄茹语" />
                    <el-option label="尹兆雨" value="尹兆雨" />
                    <el-option label="张隆铭" value="张隆铭" />
                    <el-option label="王思凯" value="王思凯" />
                    <el-option label="周思绒" value="周思绒" />
                    <el-option label="孟辰" value="孟辰" />
                    <el-option label="方天奇" value="方天奇" />
                    <el-option label="杨金龙" value="杨金龙" />
                </el-select>
            </td>
        </tr>
    </table>
</template>

<script lang="ts" setup>
import { reactive, ref, computed,onMounted } from 'vue'
import dayjs from 'dayjs'
import { useCounterStore } from "@/stores/counter"
import { ElMessage } from 'element-plus'
import { useRouter,useRoute } from 'vue-router'
import axios from 'axios'
import {read,write} from '@/axios/axiosHelper'

// Add type definitions
interface DepartmentOption {
  label: string;
  value: string;
}

interface WorkshopDepartmentMap {
  [key: string]: DepartmentOption[];
}

interface WorkshopProductionLineMap {
  [key: string]: DepartmentOption[];
}

interface TeamForm {
  teamId: string | string[];
  teamNumber: string;
  factory: string;
  workshop: string;
  department: string;
  productionLine: string;
  teams: string;
  shift: string;
  state: boolean;
  date: string;
  recorders: string;
  shiftleader: string;
  successionMonitor: string;
}

const store = useCounterStore();

const route = useRoute()
const router = useRouter()

// 生成随机业务单号的函数
const generateTeamNumber = () => {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    // 生成前四位大写英文字母
    for (let i = 0; i < 4; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    // 生成后十位数字
    for (let i = 0; i < 10; i++) {
        result += Math.floor(Math.random() * 10).toString();
    }
    return result;
}

// 获取当前时间并格式化为 ISO 8601 格式（包含年月日时分秒）
const currentDate = dayjs().format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') ;


// 定义车间和部门的映射关系
const workshopDepartmentMap: WorkshopDepartmentMap = {
    '酿造车间': [
        { label: '酿造部', value: '酿造部' }
    ],
    '糖化车间': [
        { label: '糖化部', value: '糖化部' }
    ],
    '过滤车间': [
        { label: '过滤部', value: '过滤部' }
    ]
};

// 定义车间和产线的映射关系
const workshopProductionLineMap: WorkshopProductionLineMap = {
    '酿造车间': [
        { label: '酿造一线', value: '酿造一线' },
        { label: '酿造二线', value: '酿造二线' }
    ],
    '糖化车间': [
        { label: '糖化一线', value: '糖化一线' },
        { label: '糖化二线', value: '糖化二线' }
    ],
    '过滤车间': [
        { label: '过滤一线', value: '过滤一线' },
        { label: '过滤二线', value: '过滤二线' }
    ]
};

// 部门选项
const departmentOptions = ref<DepartmentOption[]>([]);
// 产线选项
const productionLineOptions = ref<DepartmentOption[]>([]);

// do not use same name with ref
const form = reactive<TeamForm>({
    teamId: route.query.teamId,
    teamNumber: generateTeamNumber(),
    factory: '南京',
    workshop: '',
    department: '',
    productionLine: '',
    teams: '',
    shift: '',
    state: false,
    date: currentDate,
    recorders: store.counterStore.userName,
    shiftleader: '',
    successionMonitor: ''
});

onMounted(() => {
    Fan();
})

const Fan =()=>{
    read.get("p2-read/api/Team/GetTeam",{
        params:{
            teamId:route.query.teamId,
        }
    })
    .then(res=>{
        form.factory = res.data.data[0].factory;
        form.workshop = res.data.data[0].workshop;
        form.department = res.data.data[0].department;
        form.productionLine = res.data.data[0].productionLine;
        form.shift = res.data.data[0].shift;
        form.recorders = res.data.data[0].recorders;
        form.shiftleader = res.data.data[0].shiftleader;
        form.successionMonitor = res.data.data[0].successionMonitor;
        console.log("反填信息内容",res.data.data);
    })
}

// 表单验证函数
const validateForm = () => {
    if (!form.teams) {
        ElMessage.error('班组不能为空');
        return false;
    }
    if (!form.shiftleader) {
        ElMessage.error('交班班长不能为空');
        return false;
    }
    if (!form.successionMonitor) {
        ElMessage.error('接班班长不能为空');
        return false;
    }
    return true;
};

//添加交接任务
const onSubmit=()=>{
    if (!validateForm()) {
        return;
    }
    console.log('时间',form);
    write.post("p2-write/api/Team/CreateTeam",form)
    .then(res=>{
        if(res.data.code===200){
            ElMessage.success("交接班成功");
            router.push("QueryTeam");
        }
        else{
            ElMessage.error(res.data.msg);
            return;
        }
    })
    .catch(error => {
        ElMessage.error('网络请求出错，请检查网络连接');
        console.error(error);
    });
}

// 更新部门选项的函数
const updateDepartmentOptions = () => {
    const selectedWorkshop = form.workshop;
    departmentOptions.value = workshopDepartmentMap[selectedWorkshop] || [];
    form.department = ''; // 清空部门选择

    updateProductionLineOptions(); // 调用更新产线选项的函数
};

// 更新产线选项的函数
const updateProductionLineOptions = () => {
    const selectedWorkshop = form.workshop;
    productionLineOptions.value = workshopProductionLineMap[selectedWorkshop] || [];
    form.productionLine = ''; // 清空产线选择
};

// 计算属性，将状态值转换为中文描述
const stateText = computed(() => {
    return form.state? '已交接' : '待交接';
});
</script>

<style scoped>
.order-table {
    border-collapse: collapse;
    width: 100%;
}

.order-table th,
.order-table td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
}

.order-table th {
    background-color: #f2f2f2;
}
</style>

<style scoped>
#app {
    padding: 20px;
}
</style>